package org.mcjug.locationmailer;

import org.mcjug.locationmailer.receiver.ExceptionBroadcastReceiver;
import org.mcjug.locationmailer.util.AlarmManagerUtil;
import org.mcjug.locationmailer.util.EmailUtil;

import android.app.Application;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;

public class LocationMailerApplication extends Application {

    private ExceptionBroadcastReceiver exceptionBroadcastReceiver;
    private boolean isActivityRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        exceptionBroadcastReceiver = new ExceptionBroadcastReceiver();
        registerReceiver(exceptionBroadcastReceiver, new IntentFilter(getString(R.string.intentExceptionActionName)));
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                .registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {

                    @Override
                    public void onSharedPreferenceChanged(SharedPreferences prefs, String stringArg) {
                        boolean canSend = EmailUtil.canSendEmail(prefs);
                        if (!canSend) {
                            new AlarmManagerUtil(getApplicationContext()).cancelAlarm();
                        }
                    }
                });
    }

    @Override
    public void onTerminate() {
        unregisterReceiver(exceptionBroadcastReceiver);
        super.onTerminate();
    }

    public boolean isActivityRunning() {
        return isActivityRunning;
    }

    public void setActivityRunning(boolean isActivityRunning) {
        this.isActivityRunning = isActivityRunning;

    }
}
